// pages/homepage/homepage.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    categoryType: 'group',
    navbarOptions: null,
    navbarNext: 0,

    scrollY: true,
    translateX: 0,
    currentIdx: 0,
    slideAnimation: false,
  },

  /*
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (!wx.getStorageSync("login_token")) {
      wx.redirectTo({
        url: '../login/login',
      })
      return;
    }

    this.categoryType = options.categoryType;
    this.categoryid = options.categoryid;
    var scrollListHeight = app.globalData.mainpageHeight - 100;
    this.setData({
      isShow: true,
      scrollListHeight: scrollListHeight
    })

    //加载首个显示模块
    var detail = { type: 'group', id: 1 };
    if (this.categoryType && this.categoryid) {
      detail = { type: this.categoryType, id: this.categoryid };
    }
    this.navbarClick({ detail: detail });
  },


  /*
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    if (!wx.getStorageSync("login_token")) {
      return;
    }

    //检查首页数据加载
    this.checkPageData();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    var path = '/pages/homepage/homepage';
    return {
      title: '【' + this.data.myinfo.user_name + '】，该商品用星星减免超级优惠，全场包邮>>',
      path: path,
      success: () => {
      }
    }
  },

  /**
   * 检查首页数据
   */
  checkPageData: function() {
    //1秒内不重复检查
    if (this.checking) {
      return;
    }

    //开始检查数据
    this.checking = true;
    this.setData({
      checkScrollListData: true,
    })
    setTimeout(() => {
      this.checking = false;
      this.setData({
        checkScrollListData: false,
      })
    }, 1000);

    //获取navbar
    this.buildNavbar();
    //获取各类应用信息 
    if (!this.data.banners) {
      this.getAllNoticeConfig();
    }
    //更新用户信息
    this.getMyInfo();
  },

  /**
   * 创建navbar
   */
  buildNavbar: function () {
    var options = {
      item: {
        width: 56,
        height: 100,
        margin: 22,
        size: 28,
        color: '#999999',
        selectedColor: '#1f1f1f',
        animation: true,
      },
      slider: {
        width: 20,
        height: 4,
        color: '#ffda44',
      }
    };

    //查看是否需要跳转
    let storage = wx.getStorageSync('homePageTab');
    if (storage) {
      this.categoryType = 'category';
      this.categoryid = storage;
      wx.removeStorageSync('homePageTab');
      this.rebuildNavbarData(() => {
        var detail = { type: this.categoryType, id: this.categoryid, index: this.navbarIdx};
        this.navbarClick({ detail: detail });
      });
      return;
    }

    //如果还没有数据，则重新获取数据
    if (!this.data.navbarOptions) {
      this.getNavbarData(options);
    }
  },

  /**
   * 获取分组数据
   */
  getNavbarData: function (options, control) {
    app.Ajax({
      url: '/api/index.php?app=home&act=index_category',
      success: (res) => {
        var group = res.home_group || [];
        var category = res.category || [];
        group.forEach((val, index, arr) => {
          val.type = 'group';
        });
        category.forEach((val, index, arr) => {
          val.id = val.gtid;
          val.name = val.cate_name;
          val.type = 'category';
        });
        var navbarData = [].concat(group, category);
        options.data = navbarData;
        this.rebuildNavbarData(options);
      }
    })
  },

  /**
   * 重构navbar数据
   */
  rebuildNavbarData: function (navbarOptions) {
    if (typeof navbarOptions == 'function') {
      var cb = navbarOptions;
      if (this.data.navbarOptions) {
        var navOptions = this.data.navbarOptions;
        var navbarData = navOptions.data;
        var selectedIdx = 0;
        if (this.categoryType && this.categoryid) {
          navbarData.forEach((val, idx, arr) => {
            if (val.type == this.categoryType && val.id == this.categoryid) {
              selectedIdx = idx;
            }
          });
        }
        navOptions.item.selectedIdx = selectedIdx;
        this.navbarIdx = selectedIdx;

        this.setData({
          navbarOptions: navOptions
        })
        cb();
      }
      return;
    }

    if (typeof navbarOptions == 'object') {
      var navOptions = navbarOptions;
      var navbarData = navOptions.data;
      var selectedIdx = 0;
      if (this.categoryType && this.categoryid) {
        navbarData.forEach((val, idx, arr) => {
          if (val.type == this.categoryType && val.id == this.categoryid) {
            selectedIdx = idx;
          }
        });
      }
      navOptions.item.selectedIdx = selectedIdx;
      this.navbarIdx = selectedIdx;

      this.setData({
        navbarOptions: navOptions
      })
      return;
    }
  },

  /**
   * 获取二级分类数据
   */
  getSecondCategory: function (gtid) {
    app.Ajax({
      url: '/api/index.php?app=category&act=category',
      data: {
        gtid: gtid,
      },
      success: (res) => {
        res.forEach((val, idx, arr) => {
          val.id = val.gtid;
          val.name = val.cate_name;
        });
        var data = {};
        data["secondCateGoryData_" + this.data.currentIdx] = res;
        this.setData(data);
      }
    })
  },

  /**
   * 获取各类应用消息
   */
  getAllNoticeConfig: function () {
    app.Ajax({
      url: '/api/index.php?app=home&act=banner_icon_notice',
      success: (res) => {
        this.setData({
          banners: res.banners,
          announcement: res.notices,
          activity: res.home_icons,
        })
        // console.log(res)
      }
    })
  },

  /**
   * 获取我的用户信息
   */
  getMyInfo: function () {
    app.getUserInfo((res) => {
      this.setData({
        myinfo: res
      })
    })
  },

  /**
   * navbar点击回调事件
   */
  navbarClick: function (e) {
    var detailIndex = e.detail.index || 0;
    var currentIdx;
    if (Math.abs(detailIndex - this.navbarIdx) === 1) {
      if (detailIndex < this.navbarIdx) {
        currentIdx = this.data.currentIdx - 1;
        if (currentIdx < 0) {
          currentIdx = 2;
        }
      } else {
        currentIdx = this.data.currentIdx + 1;
        if (currentIdx > 2) {
          currentIdx = 0;
        }
      }
      if (currentIdx == this.preIdx) {
        this.notNeedLoadData = true;
      }
      this.preIdx = this.data.currentIdx;
    } else {
      currentIdx = 0;
      this.preIdx = null;
    }
    this.setData({
      currentIdx: currentIdx,
      translateX: 0
    })
    this.viewTranslateX = 0;

    this.navbarIdx = detailIndex;
    if (this.notNeedLoadData) {
      this.notNeedLoadData = false;
      return;
    }

    this.loadPageOptions(e);
  },

  /**
   * 加载分页配置项
   */
  loadPageOptions: function (e) {
    var id = e.detail.id;
    var type = e.detail.type;
    //分组，热门商品
    if (type == 'group') {
      var goodsOptions = {
        list_id: 'hot_goods',
        url: '/api/index.php?app=category&act=group_goods',
        data: {
          group_id: id
        }
      }
    } else {  //分类，二级分类商品
      var goodsOptions = {
        list_id: 'sec_goods',
        url: '/api/index.php?app=category&act=category_goods',
        data: {
          gtid: id
        }
      }
      this.getSecondCategory(id);
    }
    var data = {};
    for (var i = 0; i <= 2; i++) {
      if (i != this.data.currentIdx && i != this.preIdx) {
        data["goodsOptions_" + i] = null;
        data["categoryType_" + i] = null;
        data["goodsList_" + i] = null;
        data["secondCateGoryData_" + i] = null;
      }
    }
    data["categoryType_" + this.data.currentIdx] = type;
    data["goodsOptions_" + this.data.currentIdx] = goodsOptions;
    this.setData(data)
  },

  /**
   * 加载更多商品
   */
  loadMoreData: function (e) {
    if (this.data['categoryType_' + this.data.currentIdx] == 'group'
      && this.data['goodsList_' + this.data.currentIdx] == null) {
        this.checkPageData();
    }

    var data = {};
    data["goodsList_" + this.data.currentIdx] = e.detail.data;
    this.setData(data);
  },

  /**
   * 点击二级类目，进入三级类目
   */
  secCategoryClick: function (e) {
    var id = e.detail.id;
    wx.navigateTo({
      url: '../goods/goods_list/goods_list?goods_type=0&id=' + id,
    })
  },

  /**
   * 进入商品玩购页面
   */
  lookGoodsInfo: function (e) {
    var id = e.detail.id;
    wx.navigateTo({
      url: '../game/shoot/shoot?group_id=1&goods_id=' + id,
    })
  },

  /**
   * 切换navbar
   */
  navbarChange: function (sildeDirc) {
    if (sildeDirc == 'left') {
      this.setData({
        navbarNext: -1,
      })
    } else {
      this.setData({
        navbarNext: 1,
      })
    }
  },

  touchmove: function (e) {
    var scrollY = false;
    var clientX = e.changedTouches[0].clientX;
    if (this.data.scrollY === true) {
      this.setData({
        scrollY: scrollY,
      })
      this.startClientX = clientX;
      this.startTouchTime = new Date().getTime();
    }
    this.translateX = clientX - this.startClientX;
    if (this.navbarIdx == 0 && this.translateX > 0) {
      this.translateX = this.translateX / 3;
      this.startTouchTime = this.startTouchTime - 100;
    }
    if (this.navbarIdx == this.data.navbarOptions.data.length - 1 && this.translateX < 0) {
      this.translateX = this.translateX / 3;
      this.startTouchTime = this.startTouchTime - 100;
    }
    this.setData({
      translateX: this.viewTranslateX + this.translateX,
    })
  },
  touchend: function (e) {
    if (this.data.scrollY === true) {
      return;
    }

    this.endTouchTime = new Date().getTime();
    var canSlide = false;
    if (this.endTouchTime - this.startTouchTime <= 100
      && Math.abs(this.translateX) > 20) {
      canSlide = true;
    } else if (this.endTouchTime - this.startTouchTime > 100
      && Math.abs(this.translateX) > app.globalData.pageWidth / 3) {
      canSlide = true;
    }

    var sildeDirc;
    if (canSlide) {
      if (this.translateX < 0) {
        this.translateX = 0 - app.globalData.pageWidth;
        sildeDirc = 'right';
      } else {
        this.translateX = app.globalData.pageWidth;
        sildeDirc = 'left';
      }
    } else {
      this.translateX = 0;
    }
    this.translateX = this.translateX + this.viewTranslateX;
    if (this.translateX > app.globalData.pageWidth) {
      this.translateX = app.globalData.pageWidth;
    }
    if (this.translateX < -app.globalData.pageWidth) {
      this.translateX = -app.globalData.pageWidth;
    }
    this.setData({
      scrollY: true,
      translateX: this.translateX,
      slideAnimation: true
    })
    this.viewTranslateX = this.translateX
    setTimeout(() => {
      this.setData({
        slideAnimation: false
      })
      if (sildeDirc) {
        this.navbarChange(sildeDirc);
      }
    }, 300);
  },
})